<?php
namespace App\Service\Alipay;

use App\Models\ConfigureFunction; //获取配置类

use App\Service\Alipay\AlipayRsaService; //rsa签名类

class AlipayRequestService
{

    const  gateway = 'https://openapi.alipay.com/gateway.do';  //支付宝请求地址

    private $app_id; //应用ID

    public $auth_token; //用户授权

    public $method; //接口名称

    public $notify_url; //主动通知商户地址

    public $biz_content; //请求参数的集合

    public $response_key = ''; //支付宝接口相应的key

    public function __construct()
    {
        //查询支付宝APPID
        $this->app_id = ConfigureFunction::getConfigureField(42, 'app_id');
    }


    public function query()
    {

        $http_data = [
            'app_id' => $this->app_id,
            'method' => $this->method,
            'format' => 'JSON',
            'charset' => 'UTF-8',
            'sign_type' => 'RSA2',
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0',
        ];

        if ( $this->auth_token ) {
            $http_data['auth_token'] = $this->auth_token;
        }

        if ( $this->notify_url ) {
            $http_data['notify_url'] = $this->notify_url;
        }

        if (in_array($this->method, ['alipay.offline.material.image.upload', 'alipay.system.oauth.token'])) {
            $sign_data = array_merge($http_data, $this->biz_content);
        } elseif( in_array($this->method, ['alipay.marketing.card.template.modify', 'alipay.marketing.card.template.create'])) {
            $sign_data = array_merge($http_data, ['biz_content' => $this->biz_content]);
            $this->biz_content = $sign_data;
        } else {
            $sign_data = array_merge($http_data, ['biz_content' => $this->biz_content]);
            $http_data = $sign_data;
        }


        //参数签名
        $http_data['sign'] = AlipayRsaService::rsaSign( $sign_data );

        //系统参数放入GET请求串
        $requestUrl = self::gateway . '?';
        foreach ($http_data as $sysParamKey => $sysParamValue) {
            $requestUrl .= "$sysParamKey=" . urlencode( $sysParamValue ) . "&";
        }

        $requestUrl = substr($requestUrl, 0, -1);

        $request = $this->curl( $requestUrl, $this->biz_content );

        if ( $request['code'] != 200 ) {
            return ['code' => $request['code'], 'message' => $request['message']];
        }

        $res = json_decode($request['data'],true);

        if ( isset($res['error_response']['code']) &&  $res['error_response']['code'] ) {
            return ['code' => $res['error_response']['code'], 'message' => $res['error_response']['sub_msg']];
        }

        if ( isset($res[$this->response_key]['code']) && $res[$this->response_key]['code'] != 10000 ) {
            return ['code' => $res[$this->response_key]['code'], 'message' => $res[$this->response_key]['sub_msg']];
        }

        return ['code' => 200, 'message' => 'ok' , 'data' => $res[$this->response_key]];

    }


    /**
     *
     * 支付宝请求
     * @param $url
     * @param null $postFields
     * @return array
     */
    private function curl($url, $postFields = null)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $postBodyString = "";
        $encodeArray = Array();
        $postMultipart = false;

        if (is_array($postFields) && 0 < count($postFields)) {

            foreach ($postFields as $k => $v) {
                if ("@" != substr($v, 0, 1)) //判断是不是文件上传
                {

                    $postBodyString .= "$k=" . urlencode( $v ) . "&";
                    $encodeArray[$k] = $v;
                } else //文件上传用multipart/form-data，否则用www-form-urlencoded
                {
                    $postMultipart = true;
                    $encodeArray[$k] = new \CURLFile(substr($v, 1));
                }
            }

            unset ($k, $v);
            curl_setopt($ch, CURLOPT_POST, true);
            if ($postMultipart) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $encodeArray);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
            }
        }

        if ($postMultipart) {
            $headers = array('content-type: multipart/form-data;charset=UTF-8;');
        } else {
            $headers = array('content-type: application/x-www-form-urlencoded;charset=UTF-8;');
        }

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $reponse = curl_exec($ch);

        if ( curl_errno($ch) ) {
            return ['code' => 404 , 'message' => '系统错误'];
        }

        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ( $httpStatusCode != 200 ) {
            return ['code' => $httpStatusCode , 'message' => $reponse];
        }

        curl_close($ch);

        return ['code' => 200, 'message' => 'ok', 'data' => $reponse];

    }

}